﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using WebApi_SY.Entity;
using WebApi_SY.Models;

namespace WebApi_SY.Controllers
{
    public class sli_quality_reportsController : ApiController
    {
        private readonly YourDbContext _context = new YourDbContext();

        [HttpPost]
        public async Task<object> sli_quality_reportsInsert([FromBody] sli_quality_reports options)
        {
            try
            {
                var header = new sli_quality_reports
                {
                    Fformno = options.Fformno,
                    Fformid = options.Fformid,
                    Freportid = options.Freportid,
                    Fpartid = options.Fpartid,
                    Fpartno = options.Fpartno,
                    Fpartname = options.Fpartname,
                    Fqualityrank = options.Fqualityrank,
                    Fmateril = options.Fmateril,
                    Fsuppliername = options.Fsuppliername,
                    Finspectionquantity = options.Finspectionquantity,
                    Fprintstatus = options.Fprintstatus,
                    Entries = new List<sli_quality_reportsentry>()
                };

                if (options.Entries != null)
                {
                    foreach (var entry in options.Entries)
                    {
                        header.Entries.Add(new sli_quality_reportsentry
                        {
                            freportid = header.Id,
                            fformid = entry.fformid,
                            //freportid = entry.freportid,
                            foptionid = entry.foptionid,
                            foptionname = entry.foptionname,
                            fitem = entry.fitem,
                            Fno = entry.Fno,
                            ftype = entry.ftype,
                            ftechnialrequirement = entry.ftechnialrequirement,
                            fmax = entry.fmax,
                            fmin = entry.fmin,
                            fqualitytools = entry.fqualitytools,
                            fqualitytoolsname = entry.fqualitytoolsname,
                            factual = entry.factual,
                            fdiff = entry.fdiff,  // 注意：左侧变量名未以 `f` 开头，按需可改为 `fdiff`
                            serialnumber = entry.serialnumber,  // 原 `Serialnumber` 改为全小写
                            finspector = entry.finspector,
                            fdate = entry.fdate
                        });
                    }
                }

                _context.sli_quality_reports.Add(header);
                await _context.SaveChangesAsync();

                return new
                {
                    code = 200,
                    msg = "Success",
                    modelid = header.Id,
                    Date = $"{header.Id}保存成功"
                };
            }
            catch (Exception ex)
            {
                return Json(JsonConvert.SerializeObject(ex.ToString()));
            }
        }

        [HttpGet]
        public IHttpActionResult GetTableHeader(int page = 1, int pageSize = 10)
        {
            IQueryable<sli_quality_reports> query = _context.sli_quality_reports;
            var totalCount = query.Count();
            var totalPages = (int)Math.Ceiling((double)totalCount / pageSize);

            var result = query
                .OrderByDescending(b => b.Id)
                .Skip((page - 1) * pageSize)
                .Take(pageSize)
                .Select(a => new
                {
                    a.Id,
                    a.Fformno,
                    a.Fformid,
                    a.Freportid,
                    a.Fpartid,
                    a.Fpartno,
                    a.Fpartname,
                    a.Fqualityrank,
                    a.Fmateril,
                    a.Fsuppliername,
                    a.Finspectionquantity,
                    a.Fprintstatus
                });

            return Json(new
            {
                code = 200,
                msg = "OK",
                data = new
                {
                    totalCounts = totalCount,
                    totalPagess = totalPages,
                    currentPages = page,
                    pageSizes = pageSize,
                    data = result
                }
            });
        }

        [HttpGet]
        public IHttpActionResult GetTableById(int? id = null)
        {
            var query = _context.sli_quality_reports
                .Include(a => a.Entries)
                .AsQueryable();

            if (id.HasValue)
            {
                query = query.Where(q => q.Id == id);
            }

            var result = query.Select(a => new
            {
                a.Id,
                a.Fformno,
                a.Fformid,
                a.Freportid,
                a.Fpartid,
                a.Fpartno,
                a.Fpartname,
                a.Fqualityrank,
                a.Fmateril,
                Entries = a.Entries.Select(b => new
                {
                    b.ID,
                    //b.sli_quality_reportId,
                    b.fformid,
                    b.freportid,
                    b.foptionid,
                    b.foptionname,
                    b.fitem,
                    b.Fno,
                    b.ftype,
                    b.ftechnialrequirement,
                    b.fmax,
                    b.fmin,
                    b.fqualitytools,
                    b.fqualitytoolsname,
                    b.factual,
                    b.fdiff,
                    b.serialnumber,  // 原 `Serialnumber` 改为全小写
                    b.finspector,
                    b.fdate
                })
            });

            return Ok(new
            {
                code = 200,
                msg = "OK",
                data = result
            });
        }

        [HttpPost]
        public async Task<object> Update(sli_quality_reports bill)
        {
            try
            {
                var existing = await _context.sli_quality_reports
                    .Include(a => a.Entries)
                    .FirstOrDefaultAsync(a => a.Id == bill.Id);

                if (existing == null)
                {
                    return Json(new
                    {
                        code = 404,
                        msg = "Not Found",
                        date = "记录不存在"
                    });
                }

                // 更新主表字段
                existing.Fformno = bill.Fformno;
                existing.Fformid = bill.Fformid;
                existing.Freportid = bill.Freportid;
                existing.Fpartid = bill.Fpartid;
                existing.Fpartno = bill.Fpartno;
                existing.Fpartname = bill.Fpartname;
                existing.Fqualityrank = bill.Fqualityrank;
                existing.Fmateril = bill.Fmateril;
                existing.Fsuppliername = bill.Fsuppliername;
                existing.Finspectionquantity = bill.Finspectionquantity;
                existing.Fprintstatus = bill.Fprintstatus;

                // 删除原有明细
                _context.sli_quality_reportsentry.RemoveRange(existing.Entries);

                // 添加新明细
                foreach (var entry in bill.Entries)
                {
                    existing.Entries.Add(new sli_quality_reportsentry
                    {
                        //sli_quality_reportId = existing.Id,
                        fformid = entry.fformid,
                        ID = entry.freportid,  // 注意：左侧变量名未以 `f` 开头，按需可改为 `freportid`
                        foptionid = entry.foptionid,
                        foptionname = entry.foptionname,
                        fitem = entry.fitem,
                        Fno = entry.Fno,
                        ftype = entry.ftype,
                        ftechnialrequirement = entry.ftechnialrequirement,
                        fmax = entry.fmax,
                        fmin = entry.fmin,
                        fqualitytools = entry.fqualitytools,
                        fqualitytoolsname = entry.fqualitytoolsname,
                        factual = entry.factual,
                        fdiff = entry.fdiff,
                        serialnumber = entry.serialnumber,  // 原 `Serialnumber` 改为全小写
                        finspector = entry.finspector,
                        fdate = entry.fdate
                    });
                }

                await _context.SaveChangesAsync();

                return Ok(new
                {
                    code = 200,
                    msg = "Success",
                    date = $"{bill.Id}更新成功"
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    code = 500,
                    msg = "Error",
                    date = ex.Message
                });
            }
        }

        [HttpPost]
        public async Task<object> Delete(List<int> ids)
        {
            try
            {
                var headersToDelete = await _context.sli_quality_reports
                    .Where(h => ids.Contains(h.Id))
                    .Include(h => h.Entries)
                    .ToListAsync();

                if (!headersToDelete.Any())
                {
                    return Json(new
                    {
                        code = 404,
                        msg = "Not Found",
                        date = "记录不存在"
                    });
                }

                _context.sli_quality_reports.RemoveRange(headersToDelete);
                await _context.SaveChangesAsync();

                return Json(new
                {
                    code = 200,
                    msg = "Success",
                    date = $"{string.Join(",", ids)}删除成功"
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    code = 500,
                    msg = "Error",
                    date = ex.Message
                });
            }
        }
    }
}